package xyz.liut.ee.ws

import jakarta.websocket.*
import jakarta.websocket.server.ServerEndpoint
import xyz.liut.logcat.kt.logDebug
import xyz.liut.logcat.kt.logInfo
import java.io.IOException
import java.nio.ByteBuffer

@Suppress("unused")
@ServerEndpoint(value = "/ws/echo")
class Echo {

    @OnOpen
    fun onWebSocketConnect(sess: Session) {
        logInfo { "Socket Connected queryString: $sess" }
    }

    @OnMessage
    @Throws(IOException::class)
    fun onWebSocketText(sess: Session, message: String) {
        if ("PING" == message) {
            sess.basicRemote.sendText("PONG")
            logDebug { "Received TEXT message: PING" }
        } else {
            sess.basicRemote.sendText(message)
            logDebug { "Received TEXT message: $message" }
        }
    }

    @OnMessage
    @Throws(IOException::class)
    fun onWebSocketByteArray(sess: Session, message: ByteArray) {
        logDebug { "Received BYTEARRAY message: $message" }
        sess.basicRemote.sendBinary(ByteBuffer.wrap(message))
    }

    @OnClose
    fun onWebSocketClose(reason: CloseReason) {
        logInfo { "Socket Closed: $reason" }
    }

    @OnError
    fun onWebSocketError(cause: Throwable) {
        cause.printStackTrace(System.err)
    }

    @Throws(InterruptedException::class)
    fun awaitClosure() {
        logDebug { "Awaiting closure from remote" }
    }


}
